package com.tw.wi09.ws12.aps;

import java.util.Date;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;

public class APS_Main extends Service {
	private final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
	private final String TAG = "APS_Main";
	private String providerNumber, plate;
	private APS_SMS_Receiver myReceiver;
	private IntentFilter theFilter;

	private boolean runticket = false;
	private boolean businessTicket;
	private int fromTime;
	private int toTime;
	private int curTime;
	private Date time;
	private static boolean waitForSMS = false;

	public APS_Main() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		String MD = "onCreate";
		Log.d(MD, "started");

		super.onCreate();
		theFilter = new IntentFilter();
		theFilter.addAction(ACTION);
		myReceiver = new APS_SMS_Receiver();
		Toast.makeText(this, "APS_Main Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");

	}

	@Override
	public void onDestroy() {
		String MD = "onDestroy";
		Log.d(MD, "started");

		Toast.makeText(this, "APS_Main Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");
		this.unregisterReceiver(myReceiver);
		Log.d(TAG, "myReceiver_onDestroy");
	}

	@Override
	public void onStart(Intent intent, int startid) {
		super.onStart(intent, startid);
		if(intent.getAction().equals("com.tw.wi09.ws12.aps.APS_START")){
			String MD = "onStart";
			Log.d(MD, "started");

			Log.d(MD, "curTime: " + curTime);

			Toast.makeText(this, "APS_Main Started", Toast.LENGTH_LONG).show();
			Log.d(TAG, "onStart");
			Bundle b = new Bundle();
			b = intent.getExtras();
			businessTicket = b.getBoolean("Business");
			providerNumber = b.getString("Number");
			fromTime = b.getInt("Begin");
			toTime = b.getInt("End");
			plate = b.getString("Plate");
			time = new Date();
			curTime = time.getHours() * 60 + time.getMinutes();

			Log.d(MD, "businessTicket: " + businessTicket);
			Log.d(MD, "providerNumber: " + providerNumber);
			Log.d(MD, "curTime: " + curTime);
			Log.d(MD, "fromTime: " + fromTime);
			Log.d(MD, "toTime: " + toTime);
			Log.d(MD, "plate: " + plate);

			String smsOK = "Zuletzt gebuchter Parkschein in Wien: 120Min./Parkzeit: 20.10.2011 18:00 bis 20:00/ Kfz:W93671H/Preis: 2.4EUR/Restguth.:11.45EUR";

			Log.d(MD, "getTimeToFromSMS(smsOK): " + getTimeToFromSMS(smsOK));

			runSmsCheck();
		}
		else if(intent.getAction().equals("com.tw.wi09.ws12.aps.APS_SMS_RECEIVED")){
			Bundle extra = intent.getExtras();
			String number = extra.getString("Number");
			String message = extra.getString("msg");
			
			if (number.contentEquals(providerNumber)){
				int helptime =getTimeToFromSMS(message);
				if (helptime>0){
					toTime=helptime;
					waitForSMS=false;
				}
			}
			
			if (waitForSMS){
				this.registerReceiver(myReceiver, theFilter);
				Log.d(TAG, "myReceiver_onCreate");
			}
			
			
		}
		
	}

	

	/**
	 * Liefert Uhrzeit "bis" der SMS zurueck
	 * 
	 * @param value
	 * @return
	 */
	protected int getTimeToFromSMS(String value) {
		int result = 0;
		int startHour = value.indexOf("bis ") + 4;
		int doublePoint = value.indexOf(":", startHour + 1);
		int afterMinute = value.indexOf("/", doublePoint + 1);

		String hour = value.substring(startHour, doublePoint);
		String min = value.substring(doublePoint + 1, afterMinute);
		try {
			result = Integer.valueOf(hour) * 60 + Integer.valueOf(min);
		} catch (NumberFormatException e) {
			result = 0;
		}

		return result;
	}

	public void runSmsCheck() {
		String MD = "runSmsCheck";
		Log.d(MD, "started");

		Log.d(MD, "curTime: " + curTime);
		Log.d(MD, "toTime: " + toTime);

		// TODO As new Thread ? need do run in Background till endtime is
		// reached.

		// Loop till Endtime is reached
		while (curTime < toTime) {

			Log.d(MD, "curTime: " + curTime);
			Log.d(MD, "toTime: " + toTime);
			Log.d(MD, "fromTime: " + fromTime);
			Log.d(MD, "waitForSMS: " + waitForSMS);

			// If actual Time is past last fromTime
			if ((curTime > fromTime) & !waitForSMS) {
				newTicket();
				waitForSMS = true;
			}

			try {
				// 1 Minute warten
				// Thread.sleep(60000);
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			//
			time = new Date();
			curTime = time.getHours() * 60 + time.getMinutes();

			Log.d(MD, "curTime: " + curTime);
			Log.d(MD, "toTime: " + toTime);
		}
		Toast.makeText(getBaseContext(), "Endtime Reached", Toast.LENGTH_SHORT)
				.show();

		// TODO Shut of APP needed

	}

	private void newTicket() {
		String message = "";
		int diffTime;
		do {

			diffTime = toTime - fromTime;

			if (diffTime < 1) {
				break;
			} else if (diffTime < 11) {
				message = "10";
			} else if (diffTime < 31) {
				message = "30";
			} else if (diffTime < 61) {
				message = "60";
			} else if (diffTime < 91) {
				message = "90";
			} else if (diffTime < 121) {
				message = "120";
			}

			if (businessTicket) {
				message = "B" + message;
			}

			message = message + " !" + plate;

			sendParkTicketSMS(providerNumber, message);
			registerReceiver(myReceiver, theFilter);
			Log.d(TAG, "myReceiver_onCreate");

		} while (runticket);
		// test

	}

	private void sendParkTicketSMS(String phoneNumber, String message) {
		
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";

		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
				SENT), 0);

		PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
				new Intent(DELIVERED), 0);

		// ---when the SMS has been sent---
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS sent",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Toast.makeText(getBaseContext(), "Generic failure",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Toast.makeText(getBaseContext(), "No service",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Toast.makeText(getBaseContext(), "Null PDU",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Toast.makeText(getBaseContext(), "Radio off",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(SENT));

		// ---when the SMS has been delivered---
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS delivered",
							Toast.LENGTH_SHORT).show();
					break;
				case Activity.RESULT_CANCELED:
					Toast.makeText(getBaseContext(), "SMS not delivered",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(DELIVERED));
		
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);

	}
}
